package com.haiyou.sdk.thirdSdk;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSONObject;
import com.haiyou.common.system.Properties;
import com.haiyou.common.util.http.HttpUtils;
import com.haiyou.protocol.http.sdk.login.AuthRequest;

import lombok.extern.slf4j.Slf4j;

/**
 * 抖音SDK
 * 
 * @author xingyuan
 * @date 2023年12月6日 上午9:32:09
 */
@Slf4j
@Component
public class DouyinSdkService {

//	public static final String user_auth_format = "{}?appid={}&secret={}&code={}&anonymous_code={}";
	/**
	 * 正常
	 */
	public static final int code_200 = 200;

	
	/**
	 * 登录验证
	 * @param request
	 * @return uid 
	 */
	public static String authSign(AuthRequest request) {

		String baseUrl = Properties.sdk_douyin_user_auth_url();

		String code = request.getUid();
		if (code.equals("") && request.getToken().equals("")) {
			// 返回错误码
			return "";
		}
		try {
			String appId = Properties.sdk_douyin_app_id();
			
			String secret = Properties.sdk_douyin_secret();
			
			log.info("get url:{}", baseUrl);
			JSONObject body = new JSONObject();
			body.put("appid", appId);
			body.put("secret", secret);
			body.put("code", request.getUid());
			body.put("anonymous_code", request.getToken());
			log.info("body param {}", body.toJSONString());

			String response = HttpUtils.postBody(baseUrl, body.toJSONString());;

			log.info("dy response:{}", response);
			JSONObject json = JSONObject.parseObject(response);
			json  =  (JSONObject) json.get("data");
			json.remove("session_key");
			String openid = "openid";
			String anonymous_openid = "anonymous_openid";
			// 用戶id
			if (json.containsKey(openid)) {
				String roleId = json.getString(openid);
				if(!ObjectUtils.isEmpty(roleId)) {
					return roleId;
				}
			} 
			//匿名用戶id
			if (json.containsKey(anonymous_openid)) {
				String roleId = json.getString(anonymous_openid);
				if (!ObjectUtils.isEmpty(roleId)) {
					return roleId;
				}
			}
			return "";
		} catch (Exception e) {
			log.error("", e);
			return "";
		}

	}
	
	public static void main(String[] args) {
		AuthRequest x=  new AuthRequest();
		x.setUid("cIf1xVvFrc2sCRidR6qVxi-dhaqMpgAQMHYvu3hjaOU-LKxdeTJ10XA2ouuWE4xT_6b9tLlSWXKclJGrzovm2xNXPk_V6bc4r_ndOsqGzFF3bhQu4jM6whlSzTQ");
		//obbzz64mSX4iyzb3_FcY2AJzWYbA
		authSign(x);
		//https://api-sdk.essmicrogames.com/user/auth?account=2020092315165768
		//&app_id=ovdqy3we3nekjrz8&time=1600845363
		//&token=NwVe8n4zMizM1Mzg3MzZfMTYwMDg0NTM2M184MDkz
		//&sign=0aea0c2c60bb6988f83d8a8023906af5
				
		 
	}
}
